blog

home / developersection / blogs / how to handle exceptions using try, catch, finally, throw, and throws in java?

How to handle exceptions using try, catch, finally, throw, and throws in Java?

How to handle exceptions using try, catch, finally, throw, and throws in Java?

Ashutosh Kumar Verma 542 23-Jul-2024

Many keywords and constructs are used in handling exceptions in Java. Here’s how you can use try, catch, finally, throw, and throws effectively,

 

Try, catch, finally


try- This block is used to wrap code that can throw an exception.

 

catch- This block is used to handle an exception if it occurs in a try block.

 

finally- This section is optional and is used to execute important code such as cleanup code, whether an exception is thrown or not. It executes after try and catch blocks.

 

Syntax

try {
   // Code that may throw an ArithmeticException exception
   int result = divideNumbers(10, 0);
} catch (ArithmeticException e) {
   // Handle the specific exception
   System.out.println("Cannot divide by zero");
   // Optionally, you can re-throw the exception
} catch (Exception e) {
   // Handle any other exceptions not caught by previous catch blocks
   System.out.println("An error occurred");
} finally {
   // Code that executes regardless of whether an exception was thrown or caught
   // Example: Closing resources like files or database connections
   System.out.println("Cleanup code goes here");
}

 

Example-

class Program {
   public static void main(String[] args) {
       try {
           int result = divideNumbers(10, 0); // Method that throws ArithmeticException
           System.out.println("Result: " + result);
       } catch (ArithmeticException e) {
           System.out.println("Cannot divide by zero");
       } finally {
           System.out.println("Cleanup code here");
       }
   }
   
   static int divideNumbers(int a, int b)
   {
       return a/b;
   }
}

 

Output-

Cannot divide by zero
Cleanup code here


throw- This keyword is used to explicitly throw an exception from your code.

Example-
public void deposit(int amount) {
   if (amount <= 0) {
       throw new IllegalArgumentException("Deposit amount must be positive");
   }
   // Deposit logic here
}


throws- This keyword is used in the method signature to indicate that the method can throw one or more exceptions. This is part of the method declaration rather than try-catch-finally blocks.

Example-

public void withdraw(int amount) throws InsufficientFundsException {
   if (amount > balance) {
       throw new InsufficientFundsException("Insufficient funds in your account");
   } else {
       balance -= amount;
       System.out.println("Withdrawal successful");
   }
}

 


Best Practices

 

Catch specific exceptions- Catch specific exceptions first before catching more general exceptions.

 

Use finally for cleanup- Use finally for cleanup tasks to be executed whether an exception occurs or not.

Throw appropriate exceptions- Throw reasonable excuses that fit the situation.

 

Handle exceptions appropriately- Handle exceptions in a way that makes sense for your application, whether by logging, retrying, or notifying users on.


By understanding and using try, catch, finally, throw, and throws properly, you can write robust Java code that handles exceptions nicely and maintains reliability.

 

Also, Read: Differentiate between checked and unchecked exceptions in Java with examples.


Updated 23-Jul-2024

I'm a passionate content writer with a deep background in technology and web development. Skilled at writing engaging, well-researched, and SEO-friendly articles, I enjoy simplifying complex topics into clear and impactful writing that informs, inspires, and engages readers.

Leave Comment

Comments

Liked By